<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2021/7/6
 * Time: 2:55 下午
 */

namespace app\utils;


class EncryptUtils
{
    public static function shortMd5($str) {
        return substr(md5($str), 8, 16);
    }

    public static function passportEncrypt ($str, $key) { //加密函数
        srand((double)microtime() * 1000000);
        $encrypt_key = md5(rand(0, 32000));
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($str); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $encrypt_key[$ctr] . ($str[$i] ^ $encrypt_key[$ctr++]);
        }
        return base64_encode(self::passportKey($tmp, $key));
    }

    public static function passportDecrypt ($str, $key) { //解密函数
        $str = self::passportKey(base64_decode($str), $key);
        $tmp = '';
        for ($i = 0; $i < strlen($str); $i++) {
            $md5 = $str[$i];
            $tmp .= $str[++$i] ^ $md5;
        }
        return $tmp;
    }

    private static function passportKey ($str, $encrypt_key) {
        $encrypt_key = md5($encrypt_key);
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($str); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $str[$i] ^ $encrypt_key[$ctr++];
        }
        return $tmp;
    }

    public static function passowrdEncrypt ($str, $key = '12345654321') {
        $encrypt_key = md5($key);
        $encrypt_str = md5($str);
        return md5($encrypt_str . $encrypt_key);
    }
}
